//
//  PopoverPresentationController.swift
//  LVWeibo
//
//  Created by lv on 15/6/28.
//  Copyright © 2015年 lv. All rights reserved.
//

import UIKit

class PopoverPresentationController: UIPresentationController {
    
    /// 展现视图的 frame
    var presentFrame:CGRect = CGRectZero
    
    //MARK:- 重写init方法,实例化转场控制器
    override init(presentedViewController: UIViewController, presentingViewController: UIViewController) {
        // presentedViewController 是要Modal展现的视图控制器
        super.init(presentedViewController: presentedViewController, presentingViewController: presentingViewController)
        
        // 因为还没显示，容器视图还没有被创建
        print(presentedViewController)
        
        // 点击DummyView关闭展现视图
        prepareDummyView()
    }
    
    //MARK:- 创建遮罩视图
    private lazy var dummyView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.0, alpha: 0.0)
        return view
        }()
    
    //MARK:- 增加手势(点击遮罩视图关闭展现控制器)
    private func prepareDummyView() {
        let tap = UITapGestureRecognizer(target: self, action: "close")
        dummyView.addGestureRecognizer(tap)
    }
    
    // 关闭展示控制器
    func close() {
        presentedViewController.dismissViewControllerAnimated(true, completion: nil)
    }
    
    //MARK:- 容器视图重新布局子视图
    override func containerViewWillLayoutSubviews() {
        super.containerViewWillLayoutSubviews()
        
        // 添加并设置dummyView
        dummyView.frame = (containerView?.bounds)!
        containerView?.insertSubview(dummyView, atIndex: 0)
        // 设置视图的大小
        presentedView()?.frame = presentFrame
    }
}
